﻿package com.eightywork.life.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.http.client.ClientProtocolException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

/**
 * 
 * @author 80work
 * @version 0.1
 */

public class FuncUtil {

	/**
	 * 判断字符串是否为空
	 * 
	 * @param text
	 * @return
	 */
	public static boolean isNull(String text) {
		if (text == null) {
			return true;
		} else {
			if (text.length() == 0) {
				return true;
			} else {
				return false;
			}
		}
	}

	/**
	 * 如果字符串为空或者长度等于0，返回""，否则返回字符串
	 * 
	 * @param text
	 * @return
	 */
	public static String nvl(String text) {
		if (text == null) {
			return "";
		} else {
			if (text.length() == 0) {
				return "";
			} else {
				return text;
			}
		}
	}

	/**
	 * 根据出入的List对象遍历成一个 key - > 对象属性object 对应的键值对List key为List每个对象中每个属性的名称
	 * 
	 * @param list
	 * @return List<Map<String, Object>>
	 */
	static public List<Map<String, Object>> toMapList(List list) {
		try {
			List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
			for (Object o : list) {
				Map<String, Object> map = new HashMap<String, Object>();
				for (Field filed : o.getClass().getDeclaredFields()) {
					Object value = getFieldValueByName(filed.getName(), o);
					map.put(filed.getName(), value);
				}
				mapList.add(map);
			}
			return mapList;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 根据出入对象获取对象的值 前提该对象含有getter方法,方法名的命名根据Eclisp生产规范
	 * 
	 * @param fieldName
	 *            : 所要获取的属性的名称
	 * @param o
	 *            : 传入对象
	 */
	static private Object getFieldValueByName(String fieldName, Object o) {
		try {
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			Method method = o.getClass().getMethod(getter, new Class[] {});
			Object value = method.invoke(o, new Object[] {});
			return value;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 解析出url参数中的键值对 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
	 * 
	 * @param URL
	 *            url地址
	 * @return url请求参数部分
	 */
	public static Map<String, String> URLRequest(String URL) {
		Map<String, String> mapRequest = new HashMap<String, String>();
		String[] arrSplit = null;
		String strUrlParam = TruncateUrlPage(URL);
		if (strUrlParam == null) {
			return mapRequest;
		}
		// 每个键值为一组
		arrSplit = strUrlParam.split("[&]");
		for (String strSplit : arrSplit) {
			String[] arrSplitEqual = null;
			arrSplitEqual = strSplit.split("[=]");

			// 解析出键值
			if (arrSplitEqual.length > 1) {
				// 正确解析
				mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);

			} else {
				if (arrSplitEqual[0] != "") {
					// 只有参数没有值，不加入
					mapRequest.put(arrSplitEqual[0], "");
				}
			}
		}
		return mapRequest;
	}

	/**
	 * 去掉url中的路径，留下请求参数部分
	 * 
	 * @param strURL
	 *            url地址
	 * @return url请求参数部分
	 */
	public static String TruncateUrlPage(String strURL) {
		String strAllParam = null;
		String[] arrSplit = null;

		strURL = strURL.trim().toLowerCase();

		arrSplit = strURL.split("[?]");
		if (strURL.length() > 1) {
			if (arrSplit.length > 1) {
				if (arrSplit[1] != null) {
					strAllParam = arrSplit[1];
				}
			}
		}

		return strAllParam;
	}
	
//	/**
//	 * 时间戳转换
//	 * @param time， 10位时间戳
//	 * @return
//	 */
//	
//	public static long 	TIME_A_MIN	= 1000*60;
//	public static long 	TIME_A_HOUR	= TIME_A_MIN * 60;
//	public static long 	TIME_A_DAY	= TIME_A_HOUR * 24;
//	public static long  TIME_A_WEEK = TIME_A_DAY * 7;
//	public static String transTimeToString(long time)
//	{
//		// 直接转为时间
//		Date tt = new Date(time * 1000L);
//		String timeStr = "" + (tt.getYear()+1900) + "-" + 
//		getTimeIncludeZero ( (tt.getMonth()+1) +"" )
//		+ "-" + 
//		getTimeIncludeZero ( tt.getDate() + "" )
//		+ " ";
////		+ 
////		getTimeIncludeZero ( tt.getHours() + "" ) 
////		+ ":" + 
////		getTimeIncludeZero ( tt.getMinutes() + "" );
//		return timeStr;
//	}
//	public static String getTimeIncludeZero(String time)
//	{
//		if ( time.length() == 1 ) {
//			return "0" + time;
//		}
//		return time;
//	}
//	public static String transTime(long time){
//		String timeStr = "刚刚";
//		Date date = new Date(System.currentTimeMillis());
//		Date tt = new Date(time * 1000L);
//		long now 	= date.getTime();
//		long theTime = tt.getTime();
////		long flag	= time*1000;
//		long time_dif = now - theTime;
//		
//		if( time_dif >= TIME_A_WEEK || time_dif < 0 ){
//			timeStr = transTimeToString(time);
//			return timeStr;
//		}else {
//			if( time_dif > TIME_A_DAY ){
//				timeStr = (time_dif/TIME_A_DAY) + "天前";
//				return timeStr;
//			}
//			if(time_dif > TIME_A_HOUR){
//				timeStr = (time_dif/TIME_A_HOUR) + "小时前";
//				return timeStr;
//			}
//			if(time_dif > TIME_A_MIN){
//				timeStr = (time_dif/TIME_A_MIN) + "分钟前";
//				return timeStr;
//			}else {
//				timeStr = (time_dif/1000) + "秒前";
//				return timeStr;
//			}
//			
//		}
////		return timeStr;
//	}
//	
//	public static String transEndTime(long time){
//		String timeStr = "已截止";
//		Date date = new Date();
//		Date tt = new Date(time * 1000L);
//		long now 	= date.getTime();
//		long theTime = tt.getTime();
////		long flag	= time*1000;
//		long time_dif = theTime - now;
//		
//		if (time_dif <= 0) {
//			return timeStr;
//		}
//		
//		
//			if( time_dif > TIME_A_DAY ){
//				timeStr = (time_dif/TIME_A_DAY) + "天后";
//				return timeStr;
//			}
//			if(time_dif > TIME_A_HOUR){
//				timeStr = (time_dif/TIME_A_HOUR) + "小时后";
//				return timeStr;
//			}
//			if(time_dif > TIME_A_MIN){
//				timeStr = (time_dif/TIME_A_MIN) + "分钟后";
//				return timeStr;
//			}else {
//				timeStr = (time_dif/1000) + "秒后";
//				return timeStr;
//			}
//			
////		return timeStr;
//	}
//	

	public static String timeToText(String time) {
		Calendar currentTime = Calendar.getInstance();
		Calendar actionTime = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			actionTime.setTime(sdf.parse(time));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		int days = currentTime.get(Calendar.DAY_OF_YEAR)
				- actionTime.get(Calendar.DAY_OF_YEAR);
		int hours = currentTime.get(Calendar.HOUR_OF_DAY)
				- actionTime.get(Calendar.HOUR_OF_DAY);
		int minutes = currentTime.get(Calendar.MINUTE)
				- actionTime.get(Calendar.MINUTE);
		int seconds = currentTime.get(Calendar.SECOND)
				- actionTime.get(Calendar.SECOND);
		// Log.d("currentTime", sdf.format(currentTime.getTime()));
		// Log.d("time", time);
		if (days >= 7) {
			//return time.substring(0, 16);
			return time.substring(0, 10);
		} else if (days >= 1) {
			return days + "天前";
		} else if (hours >= 1) {
			return hours + "小时前";
		} else if (minutes >= 1) {
			return minutes + "分钟前";
		} else if (seconds >= 1) {
			return seconds + "秒前";
		} else {
			return "刚刚";
		}
	}
	
	public static String timeToText(long milliseconds){
		Date date = new Date();
		date.setTime(milliseconds);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return timeToText(sdf.format(date));
	}
    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     * @param str1 时间参数 1 格式：1990-01-01 12:00:00
     * @param str2 时间参数 2 格式：2009-01-01 12:00:00
     * @return String 返回值为：xx天xx小时xx分xx秒
     */ 
	public static String getDistanceTime(String str1, String str2) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date one;
		Date two;
		long day = 0;
		long hour = 0;
		long min = 0;
		long sec = 0;
		try {
			one = df.parse(str1);
			two = df.parse(str2);
			long time1 = one.getTime();
			long time2 = two.getTime();
			long diff;
			if (time1 < time2) {
				diff = time2 - time1;
			} else {
				return "结束投注";
			}
			day = diff / (24 * 60 * 60 * 1000);
			hour = (diff / (60 * 60 * 1000) - day * 24);
			min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
			sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if (day > 0) {
			return day + "天" + hour + "小时";
		} else if (hour > 0) {
			return hour + "小时" + min + "分钟";
		} else if (min > 0) {
			return min + "分钟" + sec + "秒";
		} else {
			return sec + "秒";
		}
	}
	
	public interface AfterGetImage{
		public void after(String sessionId);
	}
	
	public AfterGetImage afterGetImage;
	
	public void setAfterImage(AfterGetImage afterGetImage){
		this.afterGetImage = afterGetImage;
	}
		
    public static Bitmap getHttpBitmap(String url) throws MyHttpException {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        String cookieVal = null;  
        String sessionId = "";  
        String key = null;  
        try {
             myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
             e.printStackTrace();
        }
        try {
             HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
             conn.setConnectTimeout(5000);
             conn.setReadTimeout(5000);
             for (int i = 1; (key = conn.getHeaderFieldKey(i)) != null; i++ ) {  
                 if (key.equalsIgnoreCase("set-cookie")) {  
                     cookieVal = conn.getHeaderField(i);  
                     cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));  
                     sessionId = sessionId+cookieVal+";";
                 }  
             } 
//             if(afterGetImage != null)
//            	 afterGetImage.after(sessionId);
             InputStream is = conn.getInputStream();
             bitmap = BitmapFactory.decodeStream(is);
             is.close();
        } catch (IOException ex) {
			ex.printStackTrace();
			throw new MyHttpException("500", "网络异常请稍后再试");
		}
        return bitmap;
   }
}
